package com.jl.juc.completablefuture;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

/**
 * thenCompose和 thenCombine只能编排两个任务，多个任务需要allOf方法
 *
 * 编排对个没有依赖关系的异步任务
 *
 * 对计算结果进行合并， 所有任务都执行完之后再做某个事
 *
 */
public class CompletableFutureDemo6AllOf {

    public static void main(String[] args) {

        CompletableFuture<String> supplyAsyncA = CompletableFuture.supplyAsync(() -> {

            System.out.println(Thread.currentThread().getName() + " 来了1111");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " 结束");
            return "A";
        });


        CompletableFuture<String> supplyAsyncB = CompletableFuture.supplyAsync(() -> {

            System.out.println(Thread.currentThread().getName() + " 来了啊222");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " 结束");
            return "B";
        });

        CompletableFuture<String> supplyAsyncC = CompletableFuture.supplyAsync(() -> {

            System.out.println(Thread.currentThread().getName() + " 来了啊33333");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " 结束");
            return "C";
        });

        CompletableFuture[] array = Stream.of(supplyAsyncA, supplyAsyncB, supplyAsyncC).toArray(CompletableFuture[]::new);
        CompletableFuture<Void> all = CompletableFuture.allOf(array);
        //所有的任务已经完成
        all.thenApply((s)->{
            return Arrays.stream(array).map(f->f.join());
        });


    }

}
